package com.eeepay.eeepay_v2.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.model.IntoPiecesInfo;
import com.eeepay.eeepay_v2.util.BtnStyleUtil;
import com.eeepay.eeepay_v2.util.CardTools;
import com.eeepay.eeepay_v2.util.CheckUtils;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.eeepay_v2.util.SPUtils;
import com.eeepay.eeepay_v2.util.StatuUtils;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.util.ABRegUtil;
import com.eeepay.v2_library.view.LabelEditText;
import com.eeepay.v2_library.view.TitleBar;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.eeepay.api.grpc.nano.MerAddModular;
import cn.eeepay.api.grpc.nano.MerAddServiceGrpc;
import io.grpc.ManagedChannel;

/**
 * Created by Ching on 2016/3/10.
 * 基本资料界面
 */
public class BasicDataActivity extends ABBaseActivity implements View.OnClickListener, TitleBar.LeftBtnOnClickListener {

    private LabelEditText personLet, idLet, snoLet;
    private TextView addDeviceTv;
    private Button nextBtn;
    private LinearLayout addSNLayout;
    private TitleBar titleBar;

    private List<String> snoList = new ArrayList<>();
    //添加的sno
    private IntoPiecesInfo intoPieces;
    private String personName, personId, sno, status;
    private boolean isNext = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_basic_data;
    }

    @Override
    protected void initWidget() {
        titleBar = getViewById(R.id.tb_basic_data);
        personLet = getViewById(R.id.let_legal_person);
        idLet = getViewById(R.id.let_legal_id);
        snoLet = getViewById(R.id.let_legal_sno);
        addDeviceTv = getViewById(R.id.tv_basic_add_sno);
        nextBtn = getViewById(R.id.btn_basic_next);
        //add by zhuangzeqin 2017年4月17日13:37:23 修改按钮样式
        BtnStyleUtil.inintBtnDefaultStyle(mContext,nextBtn);
        addSNLayout = getViewById(R.id.ll_basic_data_addSn);

        idLet.getEditText().setFilters(new InputFilter[]{new InputFilter.LengthFilter(18)});
        idLet.setInputType(InputType.TYPE_CLASS_TEXT);
    }

    @Override
    protected void eventOnClick() {
        titleBar.setLeftOnClickListener(this);
        addDeviceTv.setOnClickListener(this);
        nextBtn.setOnClickListener(this);
        idLet.setEditListener(new EditListener());
        CheckUtils.addEditChangeListener(nextBtn,  R.drawable.btn_select_style, R.drawable.btn_select_style, personLet, idLet);
        initData();
    }

    private void initData() {
        intoPieces = SPUtils.getIntoPieces();
        if (intoPieces != null) {
            personLet.setEditContent(intoPieces.getLegalPerson());
            idLet.setEditContent(intoPieces.getIdCardNo());
            snoLet.setEditContent(intoPieces.getSno());
            snoList = intoPieces.getAddSnList();
        }
        if (snoList != null && snoList.size() > 0) {

            for (int i = 1; i < snoList.size(); i++) {
                addSno(snoList.get(i));
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_basic_add_sno://添加SN
                addSno(null);
                break;
            case R.id.btn_basic_next://下一步
                personName = personLet.getEditContent();
                if (!ABRegUtil.isRegiest(personName, Constant.NAME_REGEX)) {
                    showToast("请填写有效的用户名");
                    return;
                }
                if (CardTools.getInstance().checkCard(idLet.getEditContent())) {
                    showToast("请填写有效的身份证号");
                    return;
                }
                isNext = true;
                sendHttpRequest(0);
                break;
        }
    }

    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog();
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT, taskId, new GrpcUtils.AsyncTaskListener() {
            @Override
            public Object doInBack(ManagedChannel channel, int taskId) {
                MerAddServiceGrpc.MerAddServiceBlockingStub stub = MerAddServiceGrpc
                        .newBlockingStub(channel)
                        .withDeadlineAfter(5, TimeUnit.SECONDS);
                MerAddModular.IdCardNoReq regRequest = new MerAddModular.IdCardNoReq();
                regRequest.idCardNo = idLet.getEditContent();
                MerAddModular.IdCardNoRes response = stub.regAgeScope(regRequest);
                return response;
            }

            @Override
            public void updateUI(Object result, int taskId) {
                dismissProgressDialog();
                MerAddModular.IdCardNoRes response = (MerAddModular.IdCardNoRes) result;
                if (result == null) {
                    showToast("校验失败");
                    return;
                }
                if (!response.resMsg.status) {
                    showToast(response.resMsg.msg);
                    return;
                } else {
                    if (isNext) {//点击下一步才跳转
                        getCurrentValue();
                        StatuUtils.getInstance().setBasicData("已完成");
                        finish();
                        goActivity(BisInfoActivity.class);
                    }
                }
            }
        });
    }

    @Override
    public void onLeftClick(View view) {
        getCurrentValue();
        finish();
    }

    public void addSno(String sno) {
        if (TextUtils.isEmpty(snoLet.getEditContent()))
            return;
        final LabelEditText let = new LabelEditText(this);
        let.showRight(true);
        let.setRightBtnText("删除");
        let.setOnRightClickListener(new LabelEditText.RightOnClickListener() {
            @Override
            public void onRightClick(View view) {
                addSNLayout.removeView(let);
            }
        });
        let.setLabel("SN:");
        let.setEditContent(sno);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(0, 15, 0, 0);
        let.setLayoutParams(layoutParams);
        addSNLayout.addView(let);
    }

    public void setSnoList() {
        snoList = new ArrayList<>();
        snoList.add(snoLet.getEditContent());
        LabelEditText child;
        if (addSNLayout.getChildCount() > 1)
            for (int i = 1; i < addSNLayout.getChildCount(); i++) {
                child = (LabelEditText) addSNLayout.getChildAt(i);
                if (!TextUtils.isEmpty(child.getEditContent()))
                    snoList.add(child.getEditContent());
            }
    }

    /**
     * 获取当前所有输入的值
     */
    public void getCurrentValue() {
        personName = personLet.getEditContent();
        personId = idLet.getEditContent();
        sno = snoLet.getEditContent();
//        setSnoList();

        if (intoPieces != null) {
            intoPieces.setLegalPerson(personName);
            intoPieces.setIdCardNo(personId);
            intoPieces.setSno(sno);
            if (snoList != null && snoList.size() > 0)
                intoPieces.setAddSnList(snoList);
        }

        if (!TextUtils.isEmpty(personName) && !TextUtils.isEmpty(personId) && !TextUtils.isEmpty(sno)) {
            status = "已完成";
        } else {
            status = "未完成";
        }
        StatuUtils.getInstance().setBasicData(status);
        Intent intent = new Intent();
        intent.putExtra("status", status);
        setResult(RESULT_OK, intent);
        SPUtils.saveIntoPieces(intoPieces);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { //按下的如果是BACK，同时没有重复
            onLeftClick(null);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    class EditListener implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.toString().length() == 18) {
                isNext = false;
                sendHttpRequest(0);
            }
        }
    }

}
